package com.weilai.controller;

import com.weilai.controller.exceptionHandler.BusinessException;
import com.weilai.controller.exceptionHandler.Code;
import com.weilai.controller.exceptionHandler.SystemException;
import com.weilai.domain.Posts;
import com.weilai.service.CommentsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
@Api(tags = "评论相关操作", description = "对评论进行点赞")
public class CommentsController {
    @Autowired
    private CommentsService commentsService;

    // 点赞
    @ApiOperation(value = "点赞的方法")
    @PostMapping("/comments/like")
    @ResponseBody
    public Map<String,Object> like(@RequestParam int commentsId, HttpServletRequest request) {
        try {
            Object userIdObj = request.getSession().getAttribute("userId");
            if (userIdObj == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "用户未登录");
            }
            int userId = (int) userIdObj;
            return commentsService.like(userId,commentsId);
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "点赞操作失败", e);
        }
    }

    //取消点赞
    @ApiOperation(value = "取消点赞的方法")
    @PostMapping("/comments/cancelLike")
    @ResponseBody
    public Map<String,Object> cancelLike(@RequestParam int commentsId, HttpServletRequest request) {
        try {
            Object userIdObj = request.getSession().getAttribute("userId");
            if (userIdObj == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "用户未登录");
            }
            int userId = (int) userIdObj;
            return commentsService.cancelLike(userId,commentsId);
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "取消点赞失败", e);
        }
    }
}
